<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: BD<liuxingwu@duoguan.com>
 */

namespace app\admin\controller;

use app\admin\Controller;
use think\Db;
use think\facade\Config;
use think\File;
use Xin\Thinkphp5\Hint\Facade\Hint;

class UploadController extends Controller{

	/**
	 * 上传图片
	 *
	 * @param array $config
	 * @return \think\response
	 * @throws \ReflectionException
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \xin\oss\ObjectStorageException
	 */
	public function image(array $config = []){
		$file = $this->request->file('image');
		if(empty($file)) return Hint::error("没有文件上传！", 400);
		if(is_array($file)) return Hint::error("不支持多文件上传！");

		//图片查询器
		$sha1 = $file->hash();
		$item = Db::name("Picture")->where('sha1', $sha1)->where('uid', $this->user->getUserId())->find();

		if($item){ //上传文件
			$id = $item['id'];
			$path = $item['path'];
		}else{
			/** @var \xin\oss\ObjectStorageInterface $oss */
			$oss = $this->app['oss'];
			if(empty($oss)) return Hint::error('upload config not setting.', 500);

			// 合并默认配置
			$config = array_merge(Config::get('upload.image'), $config);

			// 校验文件合法性
			/**@var $info File */
			$info = $file->rule($config['rule'])->validate($config['validate']);
			if(!$info) return Hint::error($file->getError(), 400);

			// 使用tp5自带的生成规则
			$reflectionMethod = new \ReflectionMethod($file, 'buildSaveName');
			$reflectionMethod->setAccessible(true);

			// 生成key
			$key = "images/".$reflectionMethod->invoke($file, true);
			$key = str_replace("\\", "/", $key);

			$result = $oss->uploadFile($key, $file->getRealPath());
			$path = $result['url'];

			$id = Db::name("Picture")->insert([
				'uid'         => $this->user->getUserId(),
				'sha1'        => $sha1,
				'path'        => $path,
				'create_time' => $this->request->time(),
			], false, true);
		}

		//		if($this->request->getWebPublicPath()){
		//			$path = $this->request->getWebPublicPath()."/".$path;
		//		}

		return Hint::result([
			'id'  => $id,
			'url' => $path,
		]);
		//		return $this->output($path, $file, $id);
	}

	/**
	 * 输出信息
	 *
	 * @param string $path
	 * @param File   $file
	 * @param int    $id
	 * @return \think\response
	 */
	protected function output($path, $file, $id = 0){
		$source = $this->request->param('source', '', 'trim');
		if('simditor' == $source){ //编辑器上传图片
			return Hint::result([], [
				'success'   => $path ? true : false,
				'file_path' => $path ? $path : '',
			]);
		}else{
			if($path){ // 成功上传后 获取上传信息
				return Hint::result($path, ['id' => $id]);
			}else{ // 上传失败获取错误信息
				return Hint::error($file->getError());
			}
		}
	}
}
